﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using HandyControl.Controls;
using clf.weighing.entity;
using CheckBox = System.Windows.Controls.CheckBox;
using System.Diagnostics;

namespace weighing
{
    /// <summary>
    /// RoleWindow.xaml 的交互逻辑
    /// </summary>
    public partial class RoleWindow : GlowWindow
    {
        #region variables
        List<RoleVo>? mRoleVos;
        RoleVo? mRoleVo;
        private bool isSaveing = false;
        private bool IsEdit = false;
        /// <summary>
        /// 当前设置权限的角色
        /// </summary>
        private RoleVo? currSetPerRoleVo;

        private List<PermissionVo>? permissionVos;

        private List<RolePermissionVo>? rolePermissionVos;

        private Dictionary<long, CheckBox>? permiCheckboxes;
        #endregion
        public RoleWindow()
        {
            InitializeComponent();

            CommonFunction.ShowCustomIcon(this);
        }
        #region

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

        }
        private void Window_ContentRendered(object sender, EventArgs e)
        {
            LoadData();
        }
        private void Window_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Escape) this.Close();
        }
        #endregion

        private void LoadData()
        {
            mRoleVos =RoleDao.Instance.List()?.Select((i) => { return new RoleVo(i); }).ToList();
            this.DataLv.ItemsSource = mRoleVos;
        }

        private void AddBtn_Click(object sender, RoutedEventArgs e)
        {
            IsEdit = false;
            this.AddDrawerRight.IsOpen = true;
        }

        private void CancelBtn_Click(object sender, RoutedEventArgs e)
        {
            ResetInput();
            this.AddDrawerRight.IsOpen = false;
        }

        private void SaveBtn_Click(object sender, RoutedEventArgs e)
        {
            if (IsEdit)
            {
                Update();
            }
            else
            {
                Insert();
            }
        }

        private void Insert()
        {
            if (isSaveing) return;
            isSaveing = true;
            string msg;
            string name = this.nameTb.Text.Trim();
            if (name.IsNullOrEmpty() || name.Length < 2)
            {
                msg = "角色名称长度为2位以上";
                CommonFunction.AlertInfo(msg, this);
            }
            if (RoleDao.Instance.Exist(name))
            {
                msg = "角色名称已存在，不能添加。";
                CommonFunction.AlertInfo(msg, this);
            }
            Role role = new Role()
            {
                id = IdHelper.LongID,
                name = name,
                descript = this.DescriptTb.Text.Trim(),
                status = 1,
                isSevered = false
            };
            int res = RoleDao.Instance.Insert(role);
            if (res > 0)
            {
                this.AddDrawerRight.IsOpen = false;
                msg = "增加成功！";
                CommonFunction.AlertInfo(msg);
                ResetInput();
                LoadData();
            }
            else
            {
                msg = "增加失败！";
               CommonFunction.AlertInfo(msg);
            }
            isSaveing = false;
        }


        private void Update()
        {
            if (isSaveing) return;
            isSaveing = true;
            string msg;
            string name = this.nameTb.Text.Trim();
            if (name.IsNullOrEmpty() || name.Length < 2)
            {
                msg = "角色名称长度为2位以上";
                CommonFunction.AlertInfo(msg, this);
            }
            if(name != mRoleVo.Name)
            {
                if (RoleDao.Instance.Exist(name))
                {
                    msg = "角色名称已存在，不能修改。";
                    CommonFunction.AlertInfo(msg, this);
                    isSaveing=false;
                    this.saveBtn.IsChecked = false;
                    return;
                }
                mRoleVo.Name = name;
            }         
        
            mRoleVo.Descript = this.DescriptTb.Text.Trim();
            int res = RoleDao.Instance.Update(mRoleVo.mRole);
            if (res > 0)
            {
                msg = "修改成功！";
                this.AddDrawerRight.IsOpen = false;
                CommonFunction.AlertInfo(msg);
                LoadData();
                ResetInput();
            }
            else
            {
                msg = "修改失败！";
                CommonFunction.AlertInfo(msg);
            }
            isSaveing = false;
        }

        private void ResetInput()
        {
            this.saveBtn.IsChecked = false;
            this.nameTb.Text = String.Empty;
            this.DescriptTb.Text = String.Empty;
        }

        private void RefreshBtn_Click(object sender, RoutedEventArgs e)
        {
            this.LoadData();
        }
        //删除
        private void DelBtn_Click(object sender, RoutedEventArgs e)
        {
            var vo = ((RoleVo)((System.Windows.Controls.Button)sender).Tag);
            if (vo.IsSevered)
            {
                CommonFunction.AlertInfo("系统预留角色，不能删除。");
                return;
            }

            if (UserRoleDao.Instance.IsUsed(vo.Id))
            {
                CommonFunction.AlertInfo($"{vo.Name} 角色，已经被使用，不能删除。");
                return;
            }
            string msg = $"是否要删除名称为 {vo.Name} 的角色";
            var result = CommonFunction.Ask(msg, this);
            if (result == MessageBoxResult.Yes)
            {
                if (RoleDao.Instance.Delete(vo.mRole) > 0)
                {
                    LoadData();
                    CommonFunction.AlertInfo("删除成功！");
                }
                else
                {
                    CommonFunction.AlertInfo("删除失败！");
                }
            }
        }

        private void EditBtn_Click(object sender, RoutedEventArgs e)
        {
            IsEdit = true;
            mRoleVo = ((RoleVo)((System.Windows.Controls.Button)sender).Tag);
            if (mRoleVo.IsSevered)
            {
                CommonFunction.AlertInfo("系统预留角色,不能修改");
                return;
            }
            this.nameTb.Text = mRoleVo.Name;
            this.DescriptTb.Text = mRoleVo.Descript;

            this.AddDrawerRight.IsOpen = true;
        }

        #region 设置权限   
        /// <summary>
        /// 是否为第一次设置
        /// </summary>
        private bool isFirstChecked = true;
        private void SetPermission_Click(object sender, RoutedEventArgs e)
        {
            var btn = sender as System.Windows.Controls.Button;
            currSetPerRoleVo = btn?.Tag as RoleVo;
            if (currSetPerRoleVo?.Id == 1)
            {
                currSetPerRoleVo = null;
              CommonFunction.AlertInfo("该角色不需要操作");
                return;
            }
            this.PerDrawerHeader.Text = $"为 {currSetPerRoleVo?.Name} 设置权限";
            this.PermissionDrawer.IsOpen = true;
        }

        private void SelecrPerBtn_Click(object sender, RoutedEventArgs e)
        {
            if (currSetPerRoleVo?.Id == Constant.DefaultWeighingManagerId)
            {
                this.selectPerBtn.IsChecked = false;
                // CommonFunction.AlertInfo("系统默认的管理员角色，所有权限不可以修改");
                this.PermissionDrawer.IsOpen = false;
                return;
            }

            if (rolePermissionVos != null)
            {
                var data = rolePermissionVos.Select((i) => { return i.mRolePermission; }).ToList();
                int res = RolePermissionDao.Instance.Update(currSetPerRoleVo?.Id??0, data);
                if (res > 0)
                {
                    this.PermissionDrawer.IsOpen = false;
                    CommonFunction.AlertInfo("修改成功");
                    LoadData();
                }
                else
                {
                    CommonFunction.AlertInfo("修改失败");
                    this.selectPerBtn.IsChecked = false;
                }
            }
        }

        private void CancelPerBtn_Click(object sender, RoutedEventArgs e)
        {
            this.PermissionDrawer.IsOpen = false;
        }

        private void PermissionDrawer_Opened(object sender, RoutedEventArgs e)
        {
            if (permissionVos == null || permissionVos.Count <= 0)
            {
                permissionVos = PermissionDao.Instance.AllList()?.Select((i) => { return new PermissionVo(i); }).ToList();

            }
            var data = RolePermissionDao.Instance.GetListByRoleId(currSetPerRoleVo?.Id??0);
            rolePermissionVos = data.Select((i) => { return new RolePermissionVo(i); }).ToList();

            isFirstChecked = true;
            if (permiCheckboxes == null || permiCheckboxes.Count < 0)
            {
                permiCheckboxes = new Dictionary<long, CheckBox>();
                var style = FindResource("CheckBoxBaseStyle") as Style;
                for (int i = 0; i < permissionVos?.Count; i++)
                {
                    Permission p = permissionVos[i].mPermission;
                    int left = (p.level ?? 0) * 10 + 20;                  
                    var cb = new CheckBox()
                    {
                        Name = "pcb" + p.id,
                        Style = style,
                        Content = p.name,
                        IsChecked = false,
                        HorizontalAlignment =System.Windows. HorizontalAlignment.Left,
                        Tag = p,
                        Margin = new Thickness(left, 5, 20, 5),
                    };

                    foreach (var item in rolePermissionVos)
                    {
                        if (p.id == item.PermissionId)
                        {
                            cb.IsChecked = true;
                        }
                    }
                    isFirstChecked = false;
                    cb.Checked += RoleCB_Checked;
                    cb.Unchecked += RoleCB_UnChecked;
                    permiCheckboxes.Add(p.id, cb);
                }
                this.PermiPannel.Children.Clear();
                foreach (var item in permiCheckboxes)
                {
                    this.PermiPannel.Children.Add(item.Value);
                }
            }
            for (int i = 0; i < permiCheckboxes.Count; i++)
            {
                KeyValuePair<long, CheckBox> keyValuePair = permiCheckboxes.ElementAt(i);
                Permission? p = permissionVos?[i]?.mPermission;
                var cb = keyValuePair.Value;
                for (int j = 0; j < rolePermissionVos.Count; j++)
                {
                    var item = rolePermissionVos[j];
                    if (p?.id == item.PermissionId)
                    {
                        cb.IsChecked = true;
                    }
                }
            }
            isFirstChecked = false;
        }
        //未选中
        private void RoleCB_UnChecked(object sender, RoutedEventArgs e)
        {
            if (this.PermissionDrawer.IsOpen == false) return;
            CheckBox? cb = sender as CheckBox;
            if (cb != null && currSetPerRoleVo?.Id == Constant.DefaultWeighingManagerId)
            {
                CommonFunction.AlertInfo("系统默认的管理员角色，所有权限不可以修改");
                cb.IsChecked = true;
                return;
            }

            var p = cb?.Tag as Permission;
            for (int i = 0; i < rolePermissionVos?.Count; i++)
            {
                if (rolePermissionVos[i].PermissionId == p?.id)
                {
                    rolePermissionVos.Remove(rolePermissionVos[i]);
                }
            }
            //获取父类,再获取同类，没有同类选中，父类也取消
            Permission parent = FindParent(p?.parent??0);
            if (parent != null)
            {
                List<PermissionVo>? brother = permissionVos?.FindAll((pe) => { return pe.Parent == parent.id; });
                bool ishasSelect = false;
                foreach (var item in brother)
                {
                    if (permiCheckboxes?[item.Id].IsChecked == true)
                    {
                        ishasSelect = true;
                        break;
                    }
                }
                if (!ishasSelect)
                {
                    //取消上级的选择
                    CheckBox? checkBox = permiCheckboxes?[parent.id];
                    checkBox.IsChecked = false;
                }                
            }
            //取消下级的选择
            List<PermissionVo>? suns = permissionVos?.FindAll((pe) => { return pe.Parent == p?.id; });
            foreach (var item in suns)
            {
                permiCheckboxes[item.Id].IsChecked = false;
            }
        }
        //选中
        private void RoleCB_Checked(object sender, RoutedEventArgs e)
        {
            if (isFirstChecked) { return; }
            if (rolePermissionVos == null)
            {
                rolePermissionVos = new List<RolePermissionVo>();
            }
            CheckBox? cb = sender as CheckBox;
            var p = cb?.Tag as Permission;
            var rp = new RolePermissionVo(
                new RolePermission()
                {
                    id = IdHelper.LongID,
                    roleId = currSetPerRoleVo?.Id ?? 0,
                    permissionId = p?.id ?? 0
                });

            bool has = false;
            foreach (var item in rolePermissionVos)
            {
                if (item.PermissionId == p.id)
                {
                    has = true;
                }
            }
            if (!has)
            {
                rolePermissionVos.Add(new RolePermissionVo(rp.mRolePermission));
            }

            Permission parent = FindParent(p.id);
            if (parent != null)
            {
                permiCheckboxes[parent.id].IsChecked = true;
            }           
        }

        private Permission? FindParent(long parentId)
        {
            return permissionVos?.Find(p => { return p.Id == parentId; })?.mPermission;
        }

        private void PermissionDrawer_Closed(object sender, RoutedEventArgs e)
        {
            this.selectPerBtn.IsChecked = false;
            foreach (var item in permiCheckboxes)
            {
                item.Value.IsChecked = false;
            }
            this.PerDrawerHeader.Text = "设置角色";
            rolePermissionVos = null;
            currSetPerRoleVo = null;
        }
        #endregion


    }
}
